package obecto.task.conditional
{
	import obecto.event.TaskEvent;
	import obecto.task.BaseTask;

	public class IfThenElseTask extends BaseTask
	{
		public var condition : Boolean = true;
		public var conditionMethod : Function;
		public var thenTask : BaseTask;
		public var elseTask : BaseTask;
		
		protected var runningTask : BaseTask;
		
		override protected function startActual() : void
		{
			if (conditionMethod != null)
			{
				condition = conditionMethod();
			}
			
			if (condition == true)
			{
				runningTask = thenTask;
			}
			else
			{
				runningTask = elseTask;
			}
			
			if (runningTask != null)
			{
				runningTask.addEventListener(TaskEvent.COMPLETE, handleTaskComplete);
				runningTask.start();
			}
			else // there is no task specified:
			{
				addEventListener(TaskEvent.START, handleStart);
			}
		}
		
		protected function handleStart(e : TaskEvent) : void 
		{
			removeEventListener(TaskEvent.START, handleStart);
			complete();
		}
		
		protected function handleTaskComplete(e : TaskEvent) : void 
		{
			runningTask = null;
			complete();
		}
		
	}
}